
var canvas;
var ctx;

var scratchpad;

function console_log(s) {
	console.log(s);
}

function init() {
	console_log('init');
	canvas_init();
	canvas_maximize;
	scratchpad = ctx.createImageData(64, 64);
	render_clouds(scratchpad, 5, 1);
	var clip = copy_imagedata(scratchpad, 32, 32, 32, 32);
	canvas_blit(scratchpad, -30, -1);
	canvas_blit(clip, 85, 10);
}

function canvas_blit(d, x, y) {
	var ix = 0; var iy = 0;
	var nx = x; var ny = y;
	var nw = d.width; var nh = d.height;
	var nd = d;


	if (x < 0) { nx = 0; ix = - x; nw -= ix; }
	if (ix >= d.width) { return; }
	if (y < 0) { ny = 0; iy = - x; nh -= iy; }
	if (iy >= d.height) { return; }

	if (nx + nw > canvas.width) { nw = canvas.width - nw; }
	if (nw <= 0) { return; }
	if (ny + nh > canvas.height) { nh = canvas.height - nh; }
	if (nh <= 0) { return; }

	if (d.width != nw || d.height != nh) {
		nd = copy_imagedata(d, ix, iy, nw, nh);
	}

	ctx.putImageData(nd, nx, ny);
}

function copy_imagedata(d, x, y, w, h) {
	var od = ctx.createImageData(w, h);
	var row = 0;
	var col = 0;
	var i = 0;
	var j = 0;
	var c;

	for (row = 0; row < h; ++row) {
		j = ((y + row) * (d.width) + x) * 4;
		for (col = 0; col < w; ++col) {
			for (c = 0; c < 3; ++c) {
				od.data[i + c] = d.data[j + c];
			}
			od.data[i + 3] = 255;
			j += 4;
			i += 4;
		}
	}

	return od;
}

function canvas_init() {
	canvas = document.getElementById('canvas');
	ctx = canvas.getContext('2d');
	canvas_clear();
}

function canvas_maximize() {
	if (null == fixed) {
		canvas.setAttribute('width', window.innerWidth * window.devicePixelRatio);
		canvas.setAttribute('height', window.innerHeight * window.devicePixelRatio);
		//var s = 1/window.devicePixelRatio;
		//ctx.scale(s, s);
		var cw = window.innerWidth / window.devicePixelRatio;
		var ch = window.innerHeight / window.devicePixelRatio;
		canvas.style.width = window.innerWidth + 'px';
		canvas.style.height = window.innerHeight + 'px';

	} else {
		canvas.width = fixed.w;
		canvas.height = fixed.h;
		document.body.style.backgroundColor = 'gray';
	}
	click_div.style.width = window.innerWidth + 'px';
	click_div.style.height = window.innerHeight + 'px';
	ctx.globalCompositeOperation = 'lighter';
}

function canvas_clear() {
	ctx.clearRect(0, 0, canvas.width, canvas.height);
	ctx.fillStyle = "rgb(0, 0, 0)";
	ctx.fillRect(0, 0, canvas.width, canvas.height);
}

